package com.circle.view;

import javax.swing.*;
import java.awt.*;
import java.io.File;

import com.circle.model.module.ConfigData;
import com.circle.model.util.ConfigDataFactory;
import com.circle.model.util.DbUtil;
import com.circle.model.util.ResourceUtil;

public class SetPage extends JPanel {
    // 全局字体配置
    private static final String FONT_NAME = "微软雅黑";
    private static final int FONT_SIZE_NORMAL = 14;
    private static final int FONT_SIZE_LARGE = 16;
    private static final Font FONT_NORMAL = new Font(FONT_NAME, Font.PLAIN, FONT_SIZE_NORMAL);
    private static final Font FONT_BOLD = new Font(FONT_NAME, Font.BOLD, FONT_SIZE_LARGE);
    
    // 全局尺寸配置
    private static final int BUTTON_HEIGHT = 35;
    private static final int TEXTFIELD_HEIGHT = 35;
    
    // 组件
    //private JTextField pdfStoragePathField;
    private JTextField tokenField;
    private JComboBox<String> pdfNamingRuleCombo;
    //private JTextField exportField;
    private JTextField urlField;

    private ConfigData configData;

    public SetPage() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        configData = ConfigDataFactory.getInstance();

        // 创建一个包装面板，使用 FlowLayout 并设置左对齐
        JPanel wrapperPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        wrapperPanel.add(createContentPanel());

        // 将包装面板添加到 NORTH 位置，而不是 CENTER
        add(wrapperPanel, BorderLayout.NORTH);
        add(createButtonPanel(), BorderLayout.SOUTH);
    }

    private JPanel createContentPanel() {
        JPanel contentPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 参数配置标题
        gbc.gridy = 0;

        gbc.gridx = 0;
        gbc.gridwidth = 2;
        JLabel titleLabel = new JLabel("参数配置");
        titleLabel.setFont(FONT_BOLD);
        contentPanel.add(titleLabel, gbc);

        // 根目录
 /*       gbc.gridy = 1;

        gbc.gridx = 0;
        gbc.gridwidth = 1;
        JLabel pathLabel = new JLabel("文件存储根目录");
        pathLabel.setFont(FONT_NORMAL);
        contentPanel.add(pathLabel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        JPanel pathPanel = new JPanel(new BorderLayout());
        pdfStoragePathField = new JTextField("C:\\upFiles");
        pdfStoragePathField.setPreferredSize(new Dimension(500, TEXTFIELD_HEIGHT));
        pdfStoragePathField.setFont(FONT_NORMAL);
        pathPanel.add(pdfStoragePathField, BorderLayout.CENTER);
        
        JButton browseButton = new JButton("选择目录");
        browseButton.setPreferredSize(new Dimension(100, TEXTFIELD_HEIGHT));
        browseButton.setFont(FONT_NORMAL);
        pathPanel.add(browseButton, BorderLayout.EAST);
        contentPanel.add(pathPanel, gbc);
*/
        // 导出目录
        /*gbc.gridy = 2;

        gbc.gridx = 0;
        gbc.gridwidth = 1;
        JLabel exportLabel = new JLabel("导出目录");
        exportLabel.setFont(FONT_NORMAL);
        contentPanel.add(exportLabel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        JPanel exporPanel = new JPanel(new BorderLayout());
        String exportPath = ResourceUtil.getDBConfig("export.path");
        exportField = new JTextField(exportPath);
        exportField.setPreferredSize(new Dimension(500, TEXTFIELD_HEIGHT));
        exportField.setFont(FONT_NORMAL);
        exporPanel.add(exportField, BorderLayout.CENTER);

        JButton exportBrowseButton = new JButton("选择目录");
        exportBrowseButton.setPreferredSize(new Dimension(100, TEXTFIELD_HEIGHT));
        exportBrowseButton.setFont(FONT_NORMAL);
        exporPanel.add(exportBrowseButton, BorderLayout.EAST);
        contentPanel.add(exporPanel, gbc);

        configData.setExportDir(exportPath);*/

        // Token令牌
        gbc.gridy = 3;

        gbc.gridx = 0;
        gbc.gridwidth = 1;
        JLabel tokenLabel = new JLabel("Token令牌");
        tokenLabel.setFont(FONT_NORMAL);
        contentPanel.add(tokenLabel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        JPanel tokenPanel = new JPanel(new BorderLayout());
        String token = ResourceUtil.getDBConfig("dcc.token");
        tokenField = new JTextField(token);
        tokenField.setPreferredSize(new Dimension(500, TEXTFIELD_HEIGHT));
        tokenField.setFont(FONT_NORMAL);
        tokenPanel.add(tokenField, BorderLayout.CENTER);
        contentPanel.add(tokenPanel, gbc);

        configData.setToken(token);

        // 网址
        gbc.gridy = 4;

        gbc.gridx = 0;
        gbc.gridwidth = 1;
        JLabel urlLabel = new JLabel("网址");
        urlLabel.setFont(FONT_NORMAL);
        contentPanel.add(urlLabel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        JPanel urlPanel = new JPanel(new BorderLayout());
        String baseUrl = ResourceUtil.getDBConfig("base.url");
        urlField = new JTextField(baseUrl);
        urlField.setPreferredSize(new Dimension(500, TEXTFIELD_HEIGHT));
        urlField.setFont(FONT_NORMAL);
        urlPanel.add(urlField, BorderLayout.CENTER);
        contentPanel.add(urlPanel, gbc);

        configData.setUrl(baseUrl);

        // 版本
        gbc.gridy = 5;

        gbc.gridx = 0;
        gbc.gridwidth = 1;
        JLabel aboutLabel = new JLabel("关于工具");
        aboutLabel.setFont(FONT_NORMAL);
        contentPanel.add(aboutLabel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        JPanel versionPanel = new JPanel(new BorderLayout());
        // 创建只读文本区域
        JTextArea textArea = new JTextArea(3, 20);
        textArea.setText("当前版本：V 0.0.1\n版权所有：苏州赛科计算机信息系统有限公司\n发布日期：2025-01-16");
        textArea.setEditable(false);     // 设置为不可编辑
        textArea.setFocusable(false);    // 设置为不可获得焦点
        textArea.setBackground(UIManager.getColor("Panel.background")); // 使用面板背景色
        textArea.setWrapStyleWord(true); // 按单词换行
        textArea.setLineWrap(true);      // 启用自动换行
        versionPanel.add(textArea, BorderLayout.CENTER);
        contentPanel.add(versionPanel, gbc);

/*
        // PDF文件命名规则
        gbc.gridx = 0;
        gbc.gridy = 3;
        JLabel ruleLabel = new JLabel("PDF文件命名规则:");
        ruleLabel.setFont(FONT_NORMAL);
        contentPanel.add(ruleLabel, gbc);

        gbc.gridx = 1;
        String[] namingRules = {"时间戳 + 原文件名"};
        pdfNamingRuleCombo = new JComboBox<>(namingRules);
        pdfNamingRuleCombo.setPreferredSize(new Dimension(0, TEXTFIELD_HEIGHT));
        pdfNamingRuleCombo.setFont(FONT_NORMAL);
        contentPanel.add(pdfNamingRuleCombo, gbc);
*/
        // 添加目录选择事件
        /*browseButton.addActionListener(e -> {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File directory = chooser.getSelectedFile();
                pdfStoragePathField.setText(directory.getAbsolutePath());
            }
        });
        */
        /*// 添加目录选择事件
        exportBrowseButton.addActionListener(e -> {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                File directory = chooser.getSelectedFile();
                exportField.setText(directory.getAbsolutePath());
            }
        });*/
        return contentPanel;
    }

    private JPanel createButtonPanel() {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        
        JButton testConnButton = new JButton("测试连接");
        JButton resetButton = new JButton("重置");
        JButton saveButton = new JButton("保存配置");
        
        // 设置按钮样式
        testConnButton.setPreferredSize(new Dimension(100, BUTTON_HEIGHT));
        resetButton.setPreferredSize(new Dimension(80, BUTTON_HEIGHT));
        saveButton.setPreferredSize(new Dimension(100, BUTTON_HEIGHT));
        
        testConnButton.setFont(FONT_NORMAL);
        resetButton.setFont(FONT_NORMAL);
        saveButton.setFont(FONT_NORMAL);
        
        saveButton.setBackground(new Color(24, 116, 205));
        saveButton.setForeground(Color.WHITE);
        
        // 添加测试连接事件
        testConnButton.addActionListener(e -> {
            testDatabaseConnection();
        });
        
        buttonPanel.add(testConnButton);
        buttonPanel.add(resetButton);
        buttonPanel.add(saveButton);

        // 添加重置事件
        resetButton.addActionListener(e -> {
            //pdfStoragePathField.setText("C:\\upFiles");
            //exportField.setText(ResourceUtil.getDBConfig("export.path"));
            tokenField.setText(ResourceUtil.getDBConfig("dcc.token"));
            urlField.setText(ResourceUtil.getDBConfig("base.url"));
            //pdfNamingRuleCombo.setSelectedIndex(0);
        });

        // 添加保存事件
        saveButton.addActionListener(e -> {
            // TODO: 实现保存配置的逻辑
            ConfigData configData = ConfigDataFactory.getInstance();
            //configData.setDocDir(pdfStoragePathField.getText());
            //configData.setExportDir(exportField.getText());
            configData.setToken(tokenField.getText());
            configData.setUrl(urlField.getText());
            JOptionPane.showMessageDialog(this, "配置已保存", "提示", JOptionPane.INFORMATION_MESSAGE);
        });

        return buttonPanel;
    }

    // Getter方法，用于获取配置值
    /*public String getPdfStoragePath() {
        return pdfStoragePathField.getText();
    }*/

    public int getPdfSizeLimit() {
        try {
            return Integer.parseInt(tokenField.getText());
        } catch (NumberFormatException e) {
            return 10; // 默认值
        }
    }

    public String getPdfNamingRule() {
        return (String) pdfNamingRuleCombo.getSelectedItem();
    }

    // 添加测试连接方法
    private void testDatabaseConnection() {
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        
        new Thread(() -> {
            String connectionInfo = DbUtil.testConnectionWithDetails();
            String poolStats = DbUtil.getPoolStats();
            
            SwingUtilities.invokeLater(() -> {
                setCursor(Cursor.getDefaultCursor());
                
                // 创建一个更详细的消息对话框
                JTextArea textArea = new JTextArea(connectionInfo + "\n\n" + poolStats);
                textArea.setEditable(false);
                textArea.setFont(FONT_NORMAL);
                
                JScrollPane scrollPane = new JScrollPane(textArea);
                scrollPane.setPreferredSize(new Dimension(400, 200));
                
                JOptionPane.showMessageDialog(
                    this,
                    scrollPane,
                    "数据库连接测试结果",
                    connectionInfo.contains("成功") ? 
                        JOptionPane.INFORMATION_MESSAGE : 
                        JOptionPane.ERROR_MESSAGE
                );
            });
        }).start();
    }
}
